/*
 * All content copyright http://www.j2eefast.com, unless
 * otherwise indicated. All rights reserved.
 * No deletion without permission
 */
package com.j2eefast.flowable.bpm.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.j2eefast.common.core.business.annotaion.BussinessLog;
import com.j2eefast.common.core.controller.BaseController;
import com.j2eefast.common.core.enums.BusinessType;
import com.j2eefast.common.core.utils.*;
import com.j2eefast.common.db.entity.SysDatabaseEntity;
import com.j2eefast.flowable.bpm.entity.ProjectArchivesEntity;
import com.j2eefast.flowable.bpm.entity.ProjectClaimEntity;
import com.j2eefast.flowable.bpm.entity.ProjectSanLianEntity;
import com.j2eefast.flowable.bpm.mapper.SanLianMapper;
import com.j2eefast.flowable.bpm.service.ArchivesService;
import com.j2eefast.flowable.bpm.service.ProjectArchivesService;
import com.j2eefast.flowable.bpm.service.SanLianService;
import com.j2eefast.flowable.bpm.utils.MonthSheetWriteHandler;
import com.j2eefast.flowable.bpm.utils.ReadPatientExcelUtil;
import com.j2eefast.framework.annotation.RepeatSubmit;
import com.j2eefast.framework.sys.entity.SysUserEntity;
import com.j2eefast.framework.sys.service.SysUserService;
import com.j2eefast.framework.utils.Global;
import com.j2eefast.framework.utils.UserUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>三联管理</p>
 *
 * @author: zhangyuan
 * @date: 2021-04-29 00:02
 * @web: http://www.letukeji.cn
 * @version: 1.0.1
 */
@Controller
@RequestMapping("/bpm/sanlian")
public class SanlianController extends BaseController {

    private String urlPrefix = "modules/bpm/sanlian";

    @Autowired
    private SanLianService sanLianService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ArchivesService archivesService;
    @Resource
    protected SanLianMapper sanLianMapper;


    //三联单列表
    @RequestMapping("/sanlianlist")
    @RequiresPermissions("bpm:sanlian:sanlianlist")
    @ResponseBody
    public ResponseData sanlianlist(@RequestParam Map<String, Object> params) {
        PageUtil page = sanLianService.sanlianList(params);
        return success(page);
    }
    //三联单列表
    @RequiresPermissions("bpm:sanlian:sanlian")
    @GetMapping("/sanlian")
    public String archives() {
        return urlPrefix + "/sanlian";
    }


    /**
     * 删除
     */
    @RepeatSubmit
    @BussinessLog(title = "删除", businessType = BusinessType.DELETE)
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    @RequiresPermissions("bpm:sanlian:del")
    @ResponseBody
    public ResponseData deleteSanlian(HttpServletRequest request) {
        String str = request.getParameter("ids");
        if (str != "") {
            String[] s = str.split(",");
            Long[] ids = (Long[]) ConvertUtils.convert(s,Long.class);
            return sanLianService.deleteSanlian(ids) ? success() : error("删除失败!");
        } else {
            return this.error("删除失败");
        }

    }


    /**
     * 修改认领 页面
     */
    @RequiresPermissions("bpm:sanlian:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        ProjectSanLianEntity projectSanLianEntity = sanLianService.getSanlianById(id);
        mmap.put("projectSanLian", projectSanLianEntity);
        return urlPrefix + "/edit";
    }

    /**
     * 修改修改认保存
     */
    @RepeatSubmit
    @RequiresPermissions("bpm:sanlian:edit")
    @BussinessLog(title = "认领", businessType = BusinessType.UPDATE)
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData edit(ProjectSanLianEntity projectSanLianEntity) {
        ValidatorUtil.validateEntity(projectSanLianEntity);
        //查询用户信息
        SysUserEntity userEntity = sysUserService.getSysById(projectSanLianEntity.getNameId());
        projectSanLianEntity.setCeoName(userEntity.getName());


//		查询项目档案
        ProjectArchivesEntity fileEntity = archivesService.getArchivesById(projectSanLianEntity.getFileId());
        if(fileEntity!=null){
            projectSanLianEntity.setFileNumber(fileEntity.getName());
        }
        return sanLianService.updateByIds(projectSanLianEntity) ? success() : error("修改失败!");
    }

    /**
     * 新增参数配置
     */
    @RequiresPermissions("bpm:sanlian:add")
    @GetMapping("/add")
    public String add() {
        return urlPrefix + "/add";
    }

    /**
     * 新增保存
     */
    @RepeatSubmit
    @RequiresPermissions("bpm:sanlian:add")
    @BussinessLog(title = "认领", businessType = BusinessType.INSERT)
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData addSave(@Validated ProjectSanLianEntity projectSanLianEntity) {
        //校验参数
        ValidatorUtil.validateEntity(projectSanLianEntity);
        System.out.println(projectSanLianEntity.getNameId());
        //查询用户信息
        //SysUserEntity userEntity = sysUserService.getSysById(projectSanLianEntity.getNameId());
        String userName=UserUtils.getUserInfo().getName();
        projectSanLianEntity.setCeoName(userName);
        //查询项目档案
        ProjectArchivesEntity fileEntity = archivesService.getArchivesById(projectSanLianEntity.getFileId());
        if(fileEntity!=null){
            projectSanLianEntity.setFileNumber(fileEntity.getName());
        }
        return sanLianService.save(projectSanLianEntity) ? success() : error("新增失败!");
    }




//	/**
//	 * 导出
//	 */
//	@BussinessLog(title = "三联单库导出", businessType = BusinessType.EXPORT)
//	@RequiresPermissions("bpm:sanlian:export")
//	@PostMapping("/export")
//	@ResponseBody
//	public ResponseData exports(@RequestParam Map<String, Object> params) throws Exception {
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmSS");
//		String date = sdf.format(new Date());
//		String fileName =  "三联单";
//		// 表头
//		List<List<String>> heads = new ArrayList<List<String>>();
//		StringBuffer sb = new StringBuffer("三联单库查询：");
//		sb.append("表单名："+fileName + "操作时间:"+ date);
//		fileName = ToolUtil.encodingExcelFilename(fileName);
//		String folder = Global.getTempPath() + File.separator + "pio" + File.separator;
//		FileUtil.touch(folder + fileName);
//		List<ProjectSanLianEntity> listData = sanLianService.findList(params);
//		EasyExcel.write(folder + fileName, ProjectSanLianEntity.class).sheet("三联单库查询").doWrite(listData);
//		return success(fileName);
//	}



    @BussinessLog(title = "三联单库导出", businessType = BusinessType.EXPORT)
    @RequiresPermissions("bpm:sanlian:export")
    @PostMapping("/export")
    @ResponseBody
    public ResponseData export(@RequestParam Map<String, Object> params) throws Exception {
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分");
        String date = sdf.format(new Date());
        String fileName =  "三联单";
//		// 表头
//		List<List<String>> heads = new ArrayList<List<String>>();
//		StringBuffer sb = new StringBuffer("三联单库查询：");
//		sb.append("表单名："+fileName + "操作时间:"+ date);
        fileName = ToolUtil.encodingExcelFilename(fileName);
        String folder = Global.getTempPath() + File.separator + "pio" + File.separator;
//		FileUtil.touch(folder + fileName);
        List<ProjectSanLianEntity> listData = sanLianService.findList(params);
//		List pilebodysList = pilebodycheckService.pilebodystatisticsmonth(sysDepartDto, month);
//设置序号
//		for (int i = 1; i <= listData.size(); i++) {
//			listData.get(i - 1).setOrderNum(i + "");
//		}
//		response.setContentType("application / vnd.ms - excel");
//		response.setCharacterEncoding("utf - 8");
//// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
//		String fileName = URLEncoder.encode("存量建筑垃圾堆体治理进度月报表", "UTF - 8");
//		response.setHeader("Content - disposition", "attachment; filename ="+fileName + ".xls");
//内容样式策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
//垂直居中,水平居中
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
//设置 自动换行
        contentWriteCellStyle.setWrapped(true);
// 字体策略
        WriteFont contentWriteFont = new WriteFont();
// 字体大小
        contentWriteFont.setFontHeightInPoints((short) 12);
        contentWriteCellStyle.setWriteFont(contentWriteFont);
//头策略使用默认
        //excel如需下载到本地,只需要将response.getOutputStream()换成File即可(注释掉以上response代码)
        EasyExcel.write(folder + fileName, ProjectSanLianEntity.class)
                //设置输出excel版本,不设置默认为xlsx
                //.excelType(ExcelTypeEnum.XLS).head(ProjectSanLianEntity.class)
                //设置拦截器或自定义样式
                .registerWriteHandler(new MonthSheetWriteHandler())
                .registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle))
                .sheet("三联单库查询")
                //设置默认样式及写入头信息开始的行数
                .useDefaultStyle(true).relativeHeadRowIndex(3)
                //这里的addsumColomn方法是个添加合计的方法,可删除
                .doWrite(listData);
        return success(fileName);
    }







    /**
     * 导入
     */
    @RequiresPermissions("bpm:sanlian:import")
    @BussinessLog(title = "三联管理", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    @ResponseBody
    public ResponseData importSanLianSave(@RequestParam Map<String, Object> tables){
        String[] tableNames = Convert.toStrArray(tables.get("tables"));
        for(int i=0;i<tableNames.length;i++){
            System.out.println(tableNames[i]);
        }
        String dbName = (String) tables.get("dbName");
//		SysDatabaseEntity db = sysDatabaseService.getByName(dbName);
//		// 查询表信息
//		List<GenTableEntity> tableList = genTableService.generateDbTableListByNames(db, tableNames);
//		genTableService.importGenTable(tableList, UserUtils.getLoginName(),dbName);
        return success();
    }




    /**
     * 上传excel
     */
    @BussinessLog(title = "上传文件", businessType = BusinessType.UPDATE)
    @PostMapping("/upload")
    @RequiresPermissions("bpm:sanlian:upload")
    @RepeatSubmit
    @ResponseBody
    public ResponseData upload(@RequestParam("files") MultipartFile file){
        try{
            if (!file.isEmpty()){
                String pathName = FileUploadUtil.uploadFile(Global.getTempPath(), file);
                //	Map<String,String> res = new HashMap<>();
                //	int row=1;			//通过该字段标记在导入第几行
                int rowSuccess=0;		//标记成功导入的数据条数
                //	QueryWrapper<ProjectSanLianEntity> wrapper;		//mybatis-plus自带的筛选查询
                //        ReadExcel readExcel = new ReadExcel();
                List<ProjectSanLianEntity> excelInfo = ReadPatientExcelUtil.getExcelInfo(file,pathName);		//调用工具类，传入excel文件，得到数组对象
                for (ProjectSanLianEntity patientInfo : excelInfo) {
                    //	System.out.println("111111111");
                    //wrapper=new QueryWrapper<>();
                    //	row++;		//遍历插入
                    	System.out.println(patientInfo.getName());
                        System.out.println(patientInfo.getName());
                        System.out.println(patientInfo.getName());
                        System.out.println(patientInfo.getName());
                    int patientCount =sanLianService.getSanlianInfo(patientInfo.getName());
                    if (patientCount>0){//如果大于零表示已存在
                        //sanLianService.updateByIds(patientInfo);
                    }else {
                        System.out.println("444444");
                        boolean save = sanLianService.save(patientInfo);
                        //如果不存在，将数据道存到数据库
                        if (save){
                            rowSuccess++;		//保存成功后，成功数+1
                        }
                    }
                }
                return success();
            }
            return error(ToolUtil.message("sys.file.null"));
        }
        catch (Exception e)
        {
            System.out.println(e);
            return error("c出错误了"+e);
        }
    }

}
